package com.shop.vuedemo.interceptor;

import com.shop.vuedemo.annotations.NeedLogin;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * projectName: vueDemo
 * create on 2021/11/21 21:37
 *
 * @author yanbl
 * @Description :
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    /**
     * 这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin",origin);
        response.setHeader("Access-Control-Allow-Methods","*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        if (handler instanceof HandlerMethod) {
            NeedLogin needLogin = ((HandlerMethod) handler).getMethodAnnotation(NeedLogin.class);
            if (needLogin == null) {
                // 获取声明这个方法的类有没有加此注解
                needLogin = ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(NeedLogin.class);
            }

            if (needLogin != null) {
                // 在此进行判断是否登录的校验
                Object curUserContext = request.getSession().getAttribute("curUserContext");
                if (null == curUserContext) {
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write("未登录");
                    return false;
                }
            }
        }
        return true;
    }
}
